const { Client } = require('pg');
const dbConfig = require('../config/sqlconfig');
const client = new Client(dbConfig.db);

client.connect((err) => {
    if (err) {
      console.error('Failed to connect to Postgres database:', err);
    } else {
      console.log('Connected to Postgres database successfully!');
    }
  });

// 设置定时任务，每隔5分钟检查一次数据库中的Token是否过期，并删除过期的Token
setInterval(() => {
    const currentTime = Math.floor(Date.now() / 1000);
    client.query('SELECT * FROM users WHERE exp<$1', [currentTime], (err, result) => {
      if (err) {
        console.error('Failed to query database:', err);
      } else {
        result.rows.forEach((row) => {
          client.query('UPDATE users SET token=NULL, exp=NULL WHERE email=$1', [row.email], (err, result) => {
            if (err) {
              console.error('Failed to update database:', err);
            }
          });
        });
      }
    });
  }, 1000 * 60 * 1); // 每隔5分钟执行一次定时任务

module.exports = client